import {
    FieldInfo,
    MysqlError,
} from 'mysql';

import User from '../../entity/system/User';
import BaseDao from '../BaseDao';

/**
 * 用户dao的处理
 */
export default class UserDao extends BaseDao<User> {
    protected newInsance(): User {
        return new User();
    }
    protected getTableName(): string {
        return 'user';
    }
    /**
     * 通过账号查找对应的用户信息
     */
    async findByAccount(account: string): Promise<User | null> {
        let conn = this.getConn();
        return await new Promise<User | null>((resolve, reject) => {
            conn.query('select * FROM  ' + this.getTableName() + ' where _account=?', [account], (err: MysqlError | null, results?: any, fields?: FieldInfo[]) => {
                if (err) {
                    throw err
                };
                if (!results || results === null || results.length <= 0) {
                    resolve(null);
                } else {
                    resolve(Object.assign(this.newInsance(), results[0]));
                }
            });
        }).then().finally(() => {
            conn.end();
        })
    }
    /**
    * 通过电话号码查找对应的用户信息
    */
    async findByPhone(phone: string): Promise<User | null> {
        let conn = this.getConn();
        return await new Promise<User | null>((resolve, reject) => {
            conn.query('select * FROM  ' + this.getTableName() + ' where _phone=?', [phone], (err: MysqlError | null, results?: any, fields?: FieldInfo[]) => {
                if (err) {
                    throw err
                };
                if (!results || results === null || results.length <= 0) {
                    resolve(null);
                } else {
                    resolve(Object.assign(this.newInsance(), results[0]));
                }
            });
        }).then().finally(() => {
            conn.end();
        })
    }
}
